package com.tang.thepath;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.tang.thepath.db.DefaultDBHelper;
import com.tang.thepath.util.CoordinateUtil;
import com.tang.thepath.util.ScreenBroadcastListener;
import com.tang.thepath.util.ScreenManager;
import com.tang.thepath.util.ToastUtil;
import com.tang.thepath.util.WakeLockManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AMapLocationActivity extends BaseActivity {
    private static final int ACCESS_COARSE_LOCATION_CODE = 0x01;
    private static final int ACCESS_FINE_LOCATION_CODE = 0x02;
    private static final int WRITE_EXTERNAL_STORAGE_CODE = 0x03;
    private static final int READ_EXTERNAL_STORAGE_CODE = 0x04;
    private static final int READ_PHONE_STATE_CODE = 0x05;
    private DefaultDBHelper dbHelper;
    Button btnStart;
    Button btnStop;
    Button btnClear;
    Button btnTest;
    ListView listView;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;

    //List<String> logString = new ArrayList<>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ArrayAdapter<String> adapter = null;
    ScreenManager screenManager = null;
    private boolean needToBack = false;

    private String getRunningActivityName(){
        ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }

    static class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
        private static int resumed;
        private static int paused;
        private static int started;
        private static int stopped;

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            ++started;
        }

        @Override
        public void onActivityResumed(Activity activity) {
            ++resumed;
        }

        @Override
        public void onActivityPaused(Activity activity) {
            ++paused;
            android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
        }

        @Override
        public void onActivityStopped(Activity activity) {
            ++stopped;
            android.util.Log.w("test", "application is visible: " + (started > stopped));
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        public static boolean isApplicationVisible() {
            return started > stopped;
        }

        public static boolean isApplicationInForeground() {
            // 当所有 Activity 的状态中处于 resumed 的大于 paused 状态的，即可认为有Activity处于前台状态中
            return resumed > paused;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }
    private boolean isBound  = false;
    private LiveService liveService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBound = true;
            LiveService.LiveBinder binder = (LiveService.LiveBinder) service;
            liveService = binder.getService();
            Log.e("ServiceConnection","onServiceConnected");
        }

        //client 和service连接意外丢失时，会调用该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("ServiceConnection","onServiceDisconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amap_location);
        //这个确实能提升进程的优先级，在android7.1下，app切换到后台由原来的优先级11变成了3
        //startService(new Intent(this,LiveService.class));
        bindService(new Intent(this,LiveService.class),conn,BIND_AUTO_CREATE);
        dbHelper = DefaultDBHelper.getInstance(getApplicationContext());
        //Log.e("AMap",getRunningActivityName());

//        getApplication().registerActivityLifecycleCallbacks(new MyLifecycleHandler());
        screenManager  = ScreenManager.getInstance(this);
//        screenManager.startActivity();
        //这段代码，即使在不锁定进程的情况下也可以解决锁屏后的问题
        ScreenBroadcastListener listener = new ScreenBroadcastListener(this);
        listener.registerListener(new ScreenBroadcastListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
                screenManager.finishActivity();
                WakeLockManager wakeLockManager = WakeLockManager.getInstance();
                wakeLockManager.release();
                moveTaskToBack(true);
            }

            @Override
            public void onScreenOff() {
                WakeLockManager wakeLockManager = WakeLockManager.getInstance();
                wakeLockManager.acquire(getApplicationContext());
                screenManager.startActivity();

            }
        });
        /*
        0x01 Manifest.permission.ACCESS_COARSE_LOCATION,
        0x02 Manifest.permission.ACCESS_FINE_LOCATION,
        0x03 Manifest.permission.WRITE_EXTERNAL_STORAGE,
        0x04 Manifest.permission.c,
        0x05 Manifest.permission.READ_PHONE_STATE
        */
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请ACCESS_COARSE_LOCATION权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
//                    ACCESS_COARSE_LOCATION_CODE);//自定义的code
//        }

//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请ACCESS_FINE_LOCATION权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
//                    ACCESS_FINE_LOCATION_CODE);//自定义的code
//        }
//
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请WRITE_EXTERNAL_STORAGE权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    WRITE_EXTERNAL_STORAGE_CODE);//自定义的code
//        }
//
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请READ_EXTERNAL_STORAGE权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                    READ_EXTERNAL_STORAGE_CODE);//自定义的code
//        }
//
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请READ_PHONE_STATE权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
//                    READ_PHONE_STATE_CODE);//自定义的code
//        }




        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnStop = (Button) findViewById(R.id.btn_stop);
        btnClear = (Button) findViewById(R.id.btn_clear);
        btnTest = (Button) findViewById(R.id.btn_test);
        listView = (ListView) findViewById(R.id.listView);


        listView.setAdapter(adapter);
        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AMapLocationActivity.this,RepairListActivity.class));
            }
        });
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mlocationClient.startLocation();
                ToastUtil.showShort("服务已启动");
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mlocationClient.stopLocation();
                ToastUtil.showShort("服务已停止");
            }
        });
        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.clear();
                adapter.notifyDataSetChanged();
                ToastUtil.showShort("日志已清空");
            }
        });
        mlocationClient = new AMapLocationClient(getApplicationContext());
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        double lat = aMapLocation.getLatitude();
                        double lng = aMapLocation.getLongitude();
                        String type = "";
                        if(aMapLocation.getLocationType() == 1){
                            type = "GPS";
                            double latlng[] = CoordinateUtil.transformFromWGSToGCJ(aMapLocation);
                            lat=latlng[0];
                            lng=latlng[1];
                        }else if(aMapLocation.getLocationType() == 2){
                            type = "两次";
                        }else if(aMapLocation.getLocationType() == 4){
                            type = "缓存";
                        }else if(aMapLocation.getLocationType() == 5){
                            type = "wifi";
                        }else if(aMapLocation.getLocationType() == 6){
                            type = "基站";
                        }
                        //可在其中解析amapLocation获取相应内容。

                        Date date = new Date(aMapLocation.getTime());
                        String locationDate = df.format(date);//定位时间
                        String msg = "id:"+adapter.getCount()+" "+locationDate+"  lng:"+lng+"  lat:"+lat+"  type:"+type;
                        Log.e("Amap",msg);
                        adapter.add(msg);
                        adapter.notifyDataSetChanged();
                        listView.setSelection(adapter.getCount() - 1);

                        //
                        int outsignId = 0;
                        long recordTime = System.currentTimeMillis() / 1000;

                        //插入数据库
                        long id = dbHelper.insert("locations",new String[]{"outsign_id","lat","lng","record_time"},new Object[]{outsignId,String.valueOf(lat),String.valueOf(lng),recordTime});
                        doUploadLocation(id,outsignId,lat,lng,recordTime);
                    }else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError","location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setLocationCacheEnable(true);
        mLocationOption.setInterval(1000 * 60);
        mLocationOption.setMockEnable(true);
        mlocationClient.setLocationOption(mLocationOption);

    }
    protected synchronized void doUploadLocation(final long insertId, final int outsignId, final double lat, final double lng, final long record_time){
        if(Const.NETWORK_MOD == 0){
            return;
        }
        Intent intent = new Intent(this, PositionIntentService.class);
        intent.putExtra("outsign_id", outsignId);
        intent.putExtra("lat",lat);
        intent.putExtra("lng",lng);
        intent.putExtra("record_time",record_time);
        intent.putExtra("insert_id",insertId);

        startService(intent);
    }
    @Override
    protected void onPause() {
        super.onPause();
//        if(!MyLifecycleHandler.isApplicationInForeground()){
//
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        mlocationClient.stopLocation();
        mlocationClient.onDestroy();
        WakeLockManager wakeLockManager = WakeLockManager.getInstance();
        wakeLockManager.release();
        //stopService(new Intent(this,LiveService.class));
        unbindService(conn);
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(ACCESS_COARSE_LOCATION_CODE == requestCode){

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
